﻿using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Scrabble.Controls
{
    public static class Extensions
    {
        public static object GetObjectAtPoint<TItemContainer>(this ItemsControl control, Point point)
            where TItemContainer : DependencyObject
        {
            var container = GetContainerAtPoint<TItemContainer>(control, point);
            return container == null ? null : control.ItemContainerGenerator.ItemFromContainer(container);
        }

        public static TItemContainer GetContainerAtPoint<TItemContainer>(this ItemsControl control, Point point)
            where TItemContainer : DependencyObject
        {
            return VisualTreeHelper.HitTest(control, point).VisualHit.SelfWithAncestors()
                .OfType<TItemContainer>()
                .FirstOrDefault();
        }        

        public static IEnumerable<DependencyObject> SelfWithAncestors(this DependencyObject o)
        {
            while (o != null)
            {
                yield return o;
                o = VisualTreeHelper.GetParent(o);
            }
        }
    }
}